<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="作业名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入作业名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['course:homework:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:homework:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['course:homework:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['course:homework:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="homeworkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="所属课程" align="center" prop="courseName" />
      <el-table-column label="所属试卷" align="center" prop="paperName" />
      <el-table-column label="作业名称" align="center" prop="name" />
<!--      <el-table-column label="作业结束时间" align="center" prop="deadline" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.deadline) }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="未批改数" align="center" prop="unmarkNum" />-->
<!--      <el-table-column label="已批改数" align="center" prop="markedNum" />-->
<!--      <el-table-column label="未交数" align="center" prop="unsubmitNum" />-->
<!--      <el-table-column label="逻辑删除" align="center" prop="isDelete" />-->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:homework:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:homework:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handlePublish()"
            v-hasPermi="['teacher:paper:publish']"
          >发布</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--弹出框-->
    <el-drawer :title="title" :visible.sync="open" size="50%" :wrapper-closable="false">
      <!--普通表单-->
      <!-- name\duration\limitTime\startTime\endTime\notice\privilege\password -->
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="考试试卷" prop="cId">
          <el-select v-model="form.cId" :disabled="formType === 1" placeholder="请选择试卷">
            <el-option v-for="item in paperData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="考试名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="考试时长(分钟)" prop="duration">
          <el-input v-model="form.duration" type="number" />
        </el-form-item>
        <el-form-item label="限制考试时间">
          <el-switch
            v-model="form.limitTime"
            inactive-text="关闭"
            active-text="开启"
            :inactive-value="0"
            :active-value="1"
          />
        </el-form-item>
        <el-form-item v-if="form.limitTime == 1" label="考试时间设置">
          <el-date-picker
            v-model="timeValue1"
            type="datetimerange"
            range-separator="至"
            start-placeholder="考试开始时间"
            end-placeholder="考试结束时间"
          />
        </el-form-item>
        <el-form-item label="注意事项" prop="notice">
          <el-input v-model="form.notice" type="textarea" />
        </el-form-item>

        <el-form-item label="考试权限" prop="privilege">
          <el-radio v-model="form.privilege" :label="0">完全开放</el-radio>
          <el-radio v-model="form.privilege" :label="1">需要输入密码</el-radio>
        </el-form-item>

        <el-form-item v-if="form.privilege === 1" label="考试密码" prop="password">
          <el-input v-model="form.password" />
        </el-form-item>

        <div style="margin-left: 30px">
          <el-button @click="drawerVisable = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import {
  listHomework,
  getHomework,
  delHomework,
  addHomework,
  updateHomework,
  listAllHomework
} from "@/api/teacher/homework";
import {
  listAllPaper
} from '@/api/teacher/paper'

export default {
  name: "Homework",
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 作业表格数据
      homeworkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 抽屉框显示
      drawerVisable: false,
      // 表单类型（添加数据:0,修改数据:1）
      formType: 0,
      // 表格数据
      tableData: [],
      // 试卷数据
      paperData: [],
      // 记录总数
      recordTotal: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cId: null,
        pId: null,
        name: null,
        deadline: null,
        unmarkNum: null,
        markedNum: null,
        unsubmitNum: null,
        isDelete: null,
      },
      // 表单参数
      form: {
        id: null,
        name: null,
        duration: 0,
        limitTime: 0,
        startTime: null,
        endTime: null,
        notice: null,
        privilege: 0,
        password: ''
      },
      timeValue: [],
      timeValue1: [],
      // 表单校验
      rules: {
        id: [
          { required: true, message: "id不能为空", trigger: "blur" }
        ],
        cId: [
          { required: true, message: "课程ID不能为空", trigger: "blur" }
        ],
        pId: [
          { required: true, message: "试卷ID不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "作业名称不能为空", trigger: "blur" }
        ],
        deadline: [
          { required: true, message: "作业结束时间不能为空", trigger: "blur" }
        ],
        unmarkNum: [
          { required: true, message: "未批改数不能为空", trigger: "blur" }
        ],
        markedNum: [
          { required: true, message: "已批改数不能为空", trigger: "blur" }
        ],
        unsubmitNum: [
          { required: true, message: "未交数不能为空", trigger: "blur" }
        ],
        isDelete: [
          { required: true, message: "逻辑删除不能为空", trigger: "blur" }
        ],
        remark: [
          { required: true, message: "备注不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    // 获取试卷信息
    listAllPaper().then(res => {
      if (res.status === 200) {
        this.paperData = res.data
      }
    })
  },
  methods: {

    // 点击分页监听方法
    handleCurrentChange(curPage) {
      this.queryParams.pageNum = curPage
      this.queryPage()
    },

    // 查询分页
    queryPage() {
      listHomework(this.queryParams).then((res) => {
        if (res.status === 200) {
          this.tableData = res.data
          this.recordTotal = res.count
        }
      })
    },

    /** 发布作业 */
    handlePublish() {
      // console.log(this.ids)
      console.log(this.$modal);
      const id = this.ids.length === 1 ? this.ids[0] : null; // 获取选中的作业ID

      if (!id) {
        this.$modal.msgError("请选择一场作业");
        return;
      }
      console.log(`Attempting to publish exam with ID: ${id}`);
      this.$modal.confirm("确定要发布此作业吗？").then(() => {
        createWork(id).then(response => {
          this.$modal.msgSuccess("作业发布成功");
          this.getList(); // 刷新试卷列表
        }).catch(() => {
          this.$modal.msgError("作业发布失败");
        });
      });
    },
    /** 查询作业列表 */
    getList() {
      this.loading = true;
      listHomework(this.queryParams).then(response => {
        this.homeworkList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        cId: null,
        pId: null,
        name: null,
        deadline: null,
        unmarkNum: null,
        markedNum: null,
        unsubmitNum: null,
        isDelete: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加作业";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getHomework(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改作业";
      });
    },
    // 添加和更新的提交表单
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          this.$message.error('不允许提交，请检查必填项')
          return false
        } else {
          if (this.form.duration <= 0) {
            this.$message.error('考试时长应该大于0')
            return false
          }
          // 判断考试时间是否合理
          if (this.form.limitTime === 1) {
            const a = this.timeValue1[0].getTime()
            const b = this.timeValue1[1].getTime()
            const c = (b - a) / 1000 / 60
            console.log(c)
            if (c < this.form.duration) {
              this.$message.error('考试时间的范围应该大于考试时长')
              return false
            }
          }

          if (this.formType === 0) {
            // 添加记录
            addHomework(this.form).then((res) => {
              if (res.status === 200) {
                this.$message.success('添加记录成功')
                // 跳转到末尾
                listAllHomework().then((res) => {
                  this.recordTotal = res.data
                  this.queryParams.pageNum = Math.ceil(
                    this.recordTotal / this.queryParams.pageSize
                  )
                  this.handleCurrentChange(this.queryParams.pageNum)
                })
              } else {
                this.$message.error('添加记录失败')
              }
              this.drawerVisable = false // 关闭对话框
            })
          } else if (this.formType === 1) {
            // 更新记录
            updateHomework(this.form).then((res) => {
              if (res.status === 200) {
                this.$message.success('更新记录成功')
                this.queryPage()
              } else {
                this.$message.error('更新记录失败')
              }
              this.drawerVisable = false // 关闭对话框
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除作业编号为"' + ids + '"的数据项？').then(function() {
        return delHomework(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('course/homework/export', {
        ...this.queryParams
      }, `homework_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
